<template>
  <div :id="id" :class="className" :style="{ height: height, width: width }"></div>
</template>

<script>
export default {
  props: {
    className: {
      type: String,
      default: 'chart',
    },
    id: {
      type: String,
      default: 'chart',
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: '200px',
    },
    dataList: {
      type: Array,
    },
    color: {
      type: Array,
    },
    radius: {},
  },
  data() {
    return {
      chart: null,
      option: [],
    };
  },
  watch: {
    dataList(newVal) {
      if (newVal) {
        const timeout = setTimeout(() => {
          this.initChart();
          this.option.series[0].data = newVal;
          clearTimeout(timeout);
        }, 1);
      }
    },
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = this.$echarts.init(document.getElementById(this.id));
      this.option = {
        color: this.color,
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          right: 0,
          itemWidth: 8,
          itemHeight: 8,
          itemGap: 15,
          icon: 'circle',
        },
        series: [
          {
            type: 'pie',
            radius: this.radius,
            data: this.dataList,
            labelLine: {
              show: false,
            },
            label: {
              show: false,
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      };
      this.chart.setOption(this.option);
      window.addEventListener('resize', () => {
        this.chart?.resize();
      });
    },
  },
};
</script>
